<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>项目管理 - 数据收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <link href="../styles/common.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        /* Body styles are now in common.css */
        
        /* 确保模态框有足够高的z-index */
        .modal {
            z-index: 9999 !important;
        }
        .modal-backdrop {
            z-index: 9998 !important;
        }
        
        .modal-dialog {
            max-width: 90vw !important;
        }

        .navbar {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 50%, #90caf9 100%) !important;
            box-shadow: 0 4px 25px rgba(33, 150, 243, 0.15);
            border: none;
            padding: 2rem 0;
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(33, 150, 243, 0.2);
            position: relative;
            min-height: 120px;
            display: flex;
            align-items: center;
        }
        
        .navbar::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #2196f3 0%, #1976d2 50%, #2196f3 100%);
        }

        .navbar .container {
            position: relative;
            width: 100%;
            height: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
            display: grid;
            grid-template-areas: 
                "left center right"
                "left-bottom . right-bottom";
            grid-template-columns: 1fr auto 1fr;
            grid-template-rows: 1fr 1fr;
            align-items: center;
            gap: 1rem;
        }
        
        .navbar-brand {
            grid-area: center;
            font-weight: 700;
            font-size: 2rem;
            color: #1565c0 !important;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
        }

        .navbar-brand:hover {
            color: #1565c0 !important;
            text-decoration: none;
        }

        .navbar-brand i {
            margin-right: 12px;
            font-size: 1.8rem;
            color: #1565c0;
        }

        .navbar-nav {
            grid-area: left-bottom;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 0.8rem;
            justify-self: start;
        }
        
        .nav-link-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .nav-link {
            font-weight: 600;
            font-size: 0.95rem;
            color: #1565c0 !important;
            padding: 0.8rem 1.2rem !important;
            margin: 0;
            border-radius: 12px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
            text-decoration: none;
            white-space: nowrap;
            background: rgba(255, 255, 255, 0.7);
            border: 1px solid rgba(33, 150, 243, 0.2);
            backdrop-filter: blur(10px);
            min-width: 160px;
        }

        .nav-link::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(52, 152, 219, 0.1), transparent);
            transition: left 0.5s;
        }

        .nav-link:hover::before {
            left: 100%;
        }

        .nav-link:hover {
            background: linear-gradient(135deg, #ffffff 0%, #e3f2fd 100%) !important;
            color: #0d47a1 !important;
            transform: translateY(-2px) translateX(5px);
            box-shadow: 0 8px 25px rgba(33, 150, 243, 0.25);
            text-decoration: none;
            border-color: rgba(33, 150, 243, 0.4);
        }

        .nav-link i {
            margin-right: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
            color: #2196f3;
        }

        .nav-link:hover i {
            transform: scale(1.2) translateX(3px);
            color: #1976d2;
        }

        .btn-outline-light {
            grid-area: right-bottom;
            justify-self: end;
            border: 2px solid #1976d2;
            background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
            color: #ffffff !important;
            font-weight: 700;
            padding: 0.9rem 1.8rem;
            border-radius: 20px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-transform: uppercase;
            letter-spacing: 0.6px;
            font-size: 0.85rem;
            position: relative;
            overflow: hidden;
            box-shadow: 0 6px 20px rgba(33, 150, 243, 0.3);
            backdrop-filter: blur(10px);
        }

        .btn-outline-light::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.6s;
        }

        .btn-outline-light:hover::before {
            left: 100%;
        }

        .btn-outline-light:hover {
            background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%) !important;
            color: #ffffff !important;
            border-color: #1565c0;
            transform: translateY(-3px) scale(1.05);
            box-shadow: 0 12px 35px rgba(33, 150, 243, 0.4);
        }

        .btn-outline-light i {
            margin-right: 8px;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }

        .btn-outline-light:hover i {
            transform: rotate(15deg) scale(1.1);
        }
        
        .btn-outline-light:focus {
            box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.3);
            outline: none;
        }

        .container {
            margin-top: 0;
            padding-top: 20px;
        }
        
        .header h2 {
            color: #2c3e50;
            font-weight: 700;
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        
        .header h2 i {
            margin-right: 10px;
            color: #3498db;
        }
        
        .header .text-muted {
            font-size: 1.1rem;
            color: #6c757d !important;
            font-weight: 400;
        }

        .project-card {
            background: white;
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
            margin-bottom: 25px;
        }

        .project-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 20px;
            font-weight: 600;
        }

        .card-body {
            padding: 25px;
        }

        .btn {
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            border: none;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            border-radius: 25px;
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #2980b9 0%, #3498db 100%);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
        
        .btn-primary i {
            margin-right: 8px;
        }

        .btn-primary:focus {
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }

        .btn-primary:active {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(40, 167, 69, 0.3);
        }

        .btn-info {
            background: linear-gradient(135deg, #17a2b8 0%, #20c997 100%);
            color: white;
        }

        .btn-info:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(23, 162, 184, 0.3);
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(255, 193, 7, 0.3);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(220, 53, 69, 0.3);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
            color: white;
        }

        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(108, 117, 125, 0.3);
        }

        .btn-sm {
            padding: 8px 12px;
            font-size: 13px;
            min-width: 70px;
            white-space: nowrap;
        }
        
        /* 项目卡片按钮容器样式 */
        .project-buttons {
            display: flex;
            flex-wrap: nowrap;
            gap: 8px;
            justify-content: space-between;
            align-items: center;
        }
        
        .project-buttons .btn {
            flex: 1;
            min-width: 70px;
            max-width: 100px;
            padding: 6px 10px;
            font-size: 12px;
            border-radius: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* 响应式按钮调整 */
        @media (min-width: 768px) {
            .project-buttons .btn {
                min-width: 80px;
                max-width: 110px;
                padding: 8px 12px;
                font-size: 13px;
            }
        }
        
        @media (min-width: 992px) {
            .project-buttons .btn {
                min-width: 90px;
                max-width: 120px;
                padding: 8px 14px;
                font-size: 13px;
            }
        }
        
        @media (min-width: 1200px) {
            .project-buttons .btn {
                min-width: 95px;
                max-width: 125px;
                padding: 10px 16px;
                font-size: 14px;
            }
        }

        .modal-content {
            border-radius: 15px;
            border: none;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }

        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 15px 15px 0 0;
        }

        .modal-body {
            padding: 30px;
        }

        .modal-footer {
            border: none;
            padding: 20px 30px;
        }

        .btn-close {
            filter: invert(1);
        }

        .form-label {
            font-weight: 600;
            color: #555;
            margin-bottom: 8px;
        }

        .form-control, .form-select {
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            padding: 12px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-text {
            color: #6c757d;
            font-size: 14px;
        }

        .qr-code {
            max-width: 200px;
            max-height: 200px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .img-thumbnail {
            border-radius: 10px;
            border: 2px solid #e1e5e9;
        }

        .text-muted {
            color: #6c757d !important;
        }

        .badge {
            border-radius: 15px;
            padding: 0.5em 0.8em;
        }

        .badge-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .badge-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .badge-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
        }

        .badge-danger {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
        }

        #empty-state {
            background: rgba(255,255,255,0.8);
            border-radius: 15px;
            margin: 20px;
            padding: 40px;
        }

        /* Quill编辑器样式优化 */
        .ql-toolbar {
            border-radius: 8px 8px 0 0;
            border: 2px solid #e1e5e9;
            border-bottom: 1px solid #e1e5e9;
        }

        .ql-container {
            border-radius: 0 0 8px 8px;
            border: 2px solid #e1e5e9;
            border-top: none;
        }

        .ql-editor {
            min-height: 120px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 0;
                border-radius: 0;
                padding: 15px;
            }
            
            .card-body {
                padding: 20px;
            }
            
            .modal-body {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="bi bi-folder-plus"></i> 项目管理
            </a>
            <div class="ms-auto me-0">
                <button class="btn btn-outline-light" id="logout-btn">
                    <i class="bi bi-box-arrow-right"></i> 退出登录
                </button>
            </div>
        </div>
    </nav>

    <div class="container mt-0">
        <div class="header">
            <div class="mb-2">
                <div class="text-start mb-2">
                    <h2 class="mb-1 text-start"><i class="bi bi-folder2-open"></i> 我的项目</h2>
                    <p class="text-dark mb-2 text-start">管理和配置您的项目，创建表单和查看数据</p>
                </div>
                <div class="d-flex gap-2 justify-content-start">
                    <a class="btn btn-outline-light" href="/pages/admin.html">
                        <i class="bi bi-list-ul"></i> 客户数据
                    </a>
                    <a class="btn btn-outline-light" href="/pages/admin-config.html">
                        <i class="bi bi-people"></i> 管理员配置
                    </a>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createProjectModal">
                        <i class="bi bi-plus-circle"></i> 创建新项目
                    </button>
                </div>
            </div>
        </div>
        
        <div class="content">
            <div class="row">

            <div class="col-12">
                <div class="row" id="projects-container">
                    <!-- 项目卡片将在这里动态加载 -->
                </div>

                <!-- 空状态 -->
                <div class="text-center py-5" id="empty-state" style="display: none;">
                    <i class="bi bi-folder-x" style="font-size: 4rem; color: #6c757d;"></i>
                    <h4 class="text-muted mt-3">暂无项目</h4>
                    <p class="text-muted">点击上方按钮创建您的第一个项目</p>
                </div>
             </div>
         </div>
     </div>

     <!-- 创建项目模态框 -->
    <div class="modal fade" id="createProjectModal" tabindex="-1" aria-labelledby="createProjectModalLabel" aria-hidden="true" data-bs-backdrop="false" data-bs-keyboard="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createProjectModalLabel">
                        <i class="bi bi-plus-circle"></i> 创建新项目
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="create-project-form">
                        <div class="mb-3">
                            <label for="project-name" class="form-label">项目名称</label>
                            <input type="text" class="form-control" id="project-name" required>
                            <div class="form-text">请输入项目的名称，用于标识和管理</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="project-description" class="form-label">项目介绍</label>
                            <div id="project-description-editor" style="height: 150px;"></div>
                            <div class="form-text">描述项目的目标、内容和特色，支持富文本格式</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="main-image" class="form-label">项目主图</label>
                            <input type="file" class="form-control" id="main-image" accept="image/*">
                            <div class="form-text">上传项目的主要展示图片（支持 JPG、PNG、GIF 格式，最大 10MB）</div>
                            <div id="image-preview" class="mt-2" style="display: none;">
                                <small class="text-muted">图片预览：</small><br>
                                <img id="image-preview-img" src="" alt="图片预览" class="img-thumbnail" style="max-width: 200px; max-height: 150px;">
                                <div id="image-size-info" class="form-text"></div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">表单字段配置</label>
                            <div id="field-types-container">
                                <!-- 字段类型选择将在这里动态加载 -->
                            </div>
                            <div class="form-text">选择此项目需要收集的数据字段</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="create-project">
                        <i class="bi bi-check-circle"></i> 创建项目
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- QR码查看模态框 -->
    <div class="modal fade" id="qrCodeModal" tabindex="-1" data-bs-backdrop="false">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-qr-code"></i> 项目二维码
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <div id="qr-code-container">
                        <!-- QR码将在这里显示 -->
                    </div>
                    <p class="mt-3 text-muted">扫描二维码访问项目提交页面</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑项目模态框 -->
    <div class="modal fade" id="editProjectModal" tabindex="-1" data-bs-backdrop="false">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="bi bi-pencil"></i> 编辑项目
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="edit-project-form">
                        <input type="hidden" id="edit-project-id">
                        
                        <div class="mb-3">
                            <label for="edit-project-name" class="form-label">项目名称</label>
                            <input type="text" class="form-control" id="edit-project-name" required>
                            <div class="form-text">请输入项目的名称，用于标识和管理</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit-project-description" class="form-label">项目介绍</label>
                            <div id="edit-project-description-editor" style="height: 150px;"></div>
                            <div class="form-text">描述项目的目标、内容和特色，支持富文本格式</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="edit-main-image" class="form-label">项目主图</label>
                            <input type="file" class="form-control" id="edit-main-image" accept="image/*">
                            <div class="form-text">上传项目的主要展示图片（支持 JPG、PNG、GIF 格式，最大 10MB）</div>
                            <div id="edit-current-image" class="mt-2" style="display: none;">
                                <small class="text-muted">当前图片：</small><br>
                                <img id="edit-current-image-preview" src="" alt="当前项目图片" class="img-thumbnail" style="max-width: 200px; max-height: 150px;">
                            </div>
                            <div id="edit-image-preview" class="mt-2" style="display: none;">
                                <small class="text-muted">新图片预览：</small><br>
                                <img id="edit-image-preview-img" src="" alt="图片预览" class="img-thumbnail" style="max-width: 200px; max-height: 150px;">
                                <div id="edit-image-size-info" class="form-text"></div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">表单字段配置</label>
                            <div id="edit-field-types-container">
                                <!-- 字段类型选择将在这里动态加载 -->
                            </div>
                            <div class="form-text">选择此项目需要收集的数据字段</div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-edit-project">保存修改</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
    <script>
        // 初始化Quill编辑器
        let quill;
        let editQuill;
        
        // 页面加载时检查认证状态
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadFieldTypes();
            loadProjects();
            
            // 初始化富文本编辑器
            quill = new Quill('#project-description-editor', {
                theme: 'snow',
                placeholder: '请输入项目介绍...',
                modules: {
                    toolbar: [
                        ['bold', 'italic', 'underline'],
                        ['link'],
                        [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                        ['clean']
                    ]
                }
            });
            
            // 编辑项目的编辑器将在模态框显示时初始化
            
            // 监听所有模态框事件，确保页面可以滚动
            const allModals = document.querySelectorAll('.modal');
            allModals.forEach(modal => {
                modal.addEventListener('shown.bs.modal', function() {
                    // 延迟设置，避免与Bootstrap冲突
                    setTimeout(() => {
                        document.body.style.overflow = 'auto';
                        document.body.style.paddingRight = '0px';
                    }, 100);
                });
            });
            
            // 监听创建项目模态框事件
            const createModal = document.getElementById('createProjectModal');
            
            createModal.addEventListener('show.bs.modal', function() {
                // 初始化Quill编辑器（如果还没有初始化）
                if (!quill) {
                    quill = new Quill('#project-description-editor', {
                        theme: 'snow',
                        placeholder: '请输入项目介绍...',
                        modules: {
                            toolbar: [
                                ['bold', 'italic', 'underline'],
                                ['link'],
                                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                                ['clean']
                            ]
                        }
                    });
                }
            });
        });

        // 检查认证状态
        async function checkAuth() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
            
            try {
                // 获取当前用户信息
                const response = await fetch('/auth/profile', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取用户信息失败');
                }
                
                const user = await response.json();
                
                // 保存用户信息到localStorage，供其他函数使用
                localStorage.setItem('currentUser', JSON.stringify(user));
                
                // 根据用户级别控制创建项目按钮的显示
                const createBtn = document.querySelector('[data-bs-target="#createProjectModal"]');
                const pageTitle = document.querySelector('h2');
                
                if (user.level === 1) {
                    // 1级管理员可以创建项目
                    createBtn.style.display = 'block';
                    pageTitle.innerHTML = '<i class="bi bi-folder2-open"></i> 我的项目';
                } else {
                    // 2、3、4级管理员不能创建项目，但可以查看和生成二维码
                    createBtn.style.display = 'none';
                    pageTitle.innerHTML = '<i class="bi bi-folder2-open"></i> 项目列表';
                    
                    // 修改空状态提示
                    const emptyState = document.getElementById('empty-state');
                    emptyState.innerHTML = `
                        <i class="bi bi-folder-x" style="font-size: 4rem; color: #6c757d;"></i>
                        <h4 class="text-muted mt-3">暂无可用项目</h4>
                        <p class="text-muted">等待上级管理员创建项目</p>
                    `;
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                localStorage.removeItem('token');
                window.location.href = 'login.html';
            }
        }

        // 退出登录
        document.getElementById('logout-btn').addEventListener('click', function() {
            localStorage.removeItem('token');
            window.location.href = 'login.html';
        });

        // 加载项目列表
        async function loadProjects() {
            const token = localStorage.getItem('token');
            try {
                const response = await fetch('/projects', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取项目列表失败');
                }
                
                const projects = await response.json();
                displayProjects(projects);
            } catch (error) {
                console.error('加载项目列表失败:', error);
                alert('加载项目列表失败');
            }
        }

        // 显示项目列表
        function displayProjects(projects) {
            const container = document.getElementById('projects-container');
            const emptyState = document.getElementById('empty-state');
            
            if (projects.length === 0) {
                container.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }
            
            emptyState.style.display = 'none';
            container.innerHTML = projects.slice().reverse().map(project => {
                const fieldTypesHtml = project.fieldTypes && project.fieldTypes.length > 0 
                    ? project.fieldTypes.slice().reverse().map(ft => `<span class="badge bg-secondary me-1">${ft.label}</span>`).join('')
                    : '<span class="text-muted">无字段配置</span>';
                
                // 检查当前用户是否为最高管理员（level 1）
                const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
                const isTopAdmin = currentUser.level === 1;
                
                const editButtonHtml = isTopAdmin ? `
                    <button class="btn btn-outline-warning btn-sm" onclick="editProject(${project.id})">
                        <i class="bi bi-pencil"></i> 编辑
                    </button>
                ` : '';
                
                return `
                    <div class="col-md-6 col-lg-6 mb-4">
                        <div class="card project-card h-100">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="bi bi-folder"></i> ${project.name}
                                </h5>
                                <p class="card-text text-muted">
                                    <small>项目ID: ${project.id}</small>
                                </p>
                                <div class="mb-2">
                                    <small class="text-muted">表单字段:</small><br>
                                    ${fieldTypesHtml}
                                </div>
                                <div class="project-buttons">
                                    <button class="btn btn-outline-primary btn-sm" onclick="generateMyQRCode(${project.id}, '${project.name}')">
                                        <i class="bi bi-qr-code"></i> 二维码
                                    </button>
                                    <button class="btn btn-outline-info btn-sm" onclick="viewProject(${project.id})">
                                        <i class="bi bi-eye"></i> 查看
                                    </button>
                                    ${editButtonHtml}
                                </div>
                            </div>
                            <div class="card-footer text-muted">
                                <small>创建时间: ${new Date().toLocaleDateString()}</small>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 全局变量存储字段类型
        let fieldTypes = [];

        // 加载字段类型
        async function loadFieldTypes() {
            const token = localStorage.getItem('token');
            if (!token) return;

            try {
                const response = await fetch('/field-type', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    fieldTypes = await response.json();
                    displayDynamicFields();
                } else {
                    console.error('加载字段类型失败');
                }
            } catch (error) {
                console.error('加载字段类型失败:', error);
            }
        }

        // 显示动态字段选项
        function displayDynamicFields() {
            const container = document.getElementById('field-types-container');
            if (!container) {
                console.error('字段类型容器未找到');
                return;
            }
            container.innerHTML = '';

            const enabledFieldTypes = fieldTypes.filter(ft => ft.enabled);
            const halfLength = Math.ceil(enabledFieldTypes.length / 2);

            // 创建两列布局
            const leftCol = document.createElement('div');
            leftCol.className = 'col-md-6';
            const rightCol = document.createElement('div');
            rightCol.className = 'col-md-6';

            enabledFieldTypes.forEach((fieldType, index) => {
                const fieldDiv = document.createElement('div');
                fieldDiv.className = 'form-check mb-2';
                fieldDiv.innerHTML = `
                    <input class="form-check-input" type="checkbox" id="field-${fieldType.key}" name="fieldTypes" value="${fieldType.id}" ${fieldType.required ? 'checked' : ''}>
                    <label class="form-check-label" for="field-${fieldType.key}">${fieldType.label}</label>
                `;

                if (index < halfLength) {
                    leftCol.appendChild(fieldDiv);
                } else {
                    rightCol.appendChild(fieldDiv);
                }
            });

            container.appendChild(leftCol);
            container.appendChild(rightCol);
        }

        // 获取选中的字段类型ID
        function getSelectedFieldTypeIds() {
            const checkboxes = document.querySelectorAll('input[name="fieldTypes"]:checked');
            return Array.from(checkboxes).map(checkbox => parseInt(checkbox.value));
        }

        // 图片预览功能
        document.getElementById('main-image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('image-preview');
            const previewImg = document.getElementById('image-preview-img');
            const sizeInfo = document.getElementById('image-size-info');
            
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.style.display = 'block';
                    if (sizeInfo) {
                        const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
                        sizeInfo.textContent = `文件大小：${sizeMB}MB`;
                    }
                };
                reader.readAsDataURL(file);
            } else {
                preview.style.display = 'none';
                if (sizeInfo) sizeInfo.textContent = '';
            }
        });

        // 创建项目
        document.getElementById('create-project').addEventListener('click', async function() {
            const projectName = document.getElementById('project-name').value.trim();
            const projectDescription = quill.root.innerHTML.trim();
            const mainImageFile = document.getElementById('main-image').files[0];
            const selectedFieldTypeIds = getSelectedFieldTypeIds();
            
            // 检查是否至少选择了一个字段
            if (selectedFieldTypeIds.length === 0) {
                alert('请至少选择一个表单字段');
                return;
            }
            
            if (!projectName) {
                alert('请输入项目名称');
                return;
            }
            
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }
            let mainImagePath = null;
            
            try {
                if (!navigator.onLine) {
                    throw new Error('网络连接不可用，请检查网络后重试');
                }
                // 如果有图片文件，先上传图片
                if (mainImageFile) {
                    // 客户端校验大小、类型与扩展名，减少请求与明确错误提示
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                    const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
                    const lowerName = (mainImageFile.name || '').toLowerCase();
                    if (!allowedTypes.includes(mainImageFile.type)) {
                        throw new Error('不支持的图片格式，请使用 JPG、PNG 或 GIF');
                    }
                    if (!allowedExts.some(ext => lowerName.endsWith(ext))) {
                        throw new Error('文件扩展名不被支持，请使用 .jpg / .jpeg / .png / .gif');
                    }
                    if (mainImageFile.size > 10 * 1024 * 1024) {
                        const sizeMB = (mainImageFile.size / (1024 * 1024)).toFixed(2);
                        throw new Error(`图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试`);
                    }

                    const formData = new FormData();
                    formData.append('file', mainImageFile);
                    
                    const uploadResponse = await fetch('/projects/upload', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        },
                        body: formData
                    });
                    
                    if (!uploadResponse.ok) {
                        let serverMessage = '';
                        try {
                            const errData = await uploadResponse.json();
                            serverMessage = errData.message || errData.error || '';
                        } catch (e) {
                            try {
                                serverMessage = await uploadResponse.text();
                            } catch (_) {}
                        }

                        // 按状态码与消息细化提示
                        if (uploadResponse.status === 401) {
                            throw new Error('未登录或登录已过期，请重新登录');
                        }
                        if (uploadResponse.status === 404) {
                            throw new Error('上传接口不可用或服务未启动，请稍后重试');
                        }
                        if (uploadResponse.status === 413) {
                            const sizeMB = mainImageFile ? (mainImageFile.size / (1024 * 1024)).toFixed(2) : null;
                            throw new Error(sizeMB ? `图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试` : '图片过大，超过 10MB 限制，请压缩后重试');
                        }
                        if (uploadResponse.status === 415) {
                            throw new Error('媒体类型不被支持，请使用 JPG、PNG 或 GIF');
                        }
                        if (serverMessage.includes('Only image files are allowed')) {
                            throw new Error('不支持的图片格式，请使用 JPG、PNG 或 GIF');
                        }
                        if (serverMessage.includes('No file uploaded')) {
                            throw new Error('未选择图片文件，请先选择后再上传');
                        }
                        if (serverMessage.includes('File too large') || serverMessage.includes('LIMIT_FILE_SIZE')) {
                            const sizeMB = mainImageFile ? (mainImageFile.size / (1024 * 1024)).toFixed(2) : null;
                            throw new Error(sizeMB ? `图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试` : '图片过大，超过 10MB 限制，请压缩后重试');
                        }
                        if (uploadResponse.status === 500) {
                            throw new Error('服务器内部错误' + (serverMessage ? `：${serverMessage}` : '，请稍后重试或联系管理员'));
                        }

                        throw new Error('图片上传失败' + (serverMessage ? `：${serverMessage}` : `（HTTP ${uploadResponse.status}）`));
                    }
                    
                    const uploadResult = await uploadResponse.json();
                    mainImagePath = uploadResult.path;
                }
                
                // 创建项目
                const projectData = {
                    name: projectName,
                    description: projectDescription || undefined,
                    mainImage: mainImagePath || undefined,
                    fieldTypeIds: selectedFieldTypeIds
                };
                
                const response = await fetch('/projects', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(projectData)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '创建项目失败');
                }
                
                const project = await response.json();
                bootstrap.Modal.getInstance(document.getElementById('createProjectModal')).hide();
                
                // 清空表单
                document.getElementById('project-name').value = '';
                quill.setText('');
                document.getElementById('main-image').value = '';
                document.getElementById('image-preview').style.display = 'none';
                
                // 重置字段选择
                const checkboxes = document.querySelectorAll('input[name="fieldTypes"]');
                checkboxes.forEach(checkbox => {
                    const fieldType = fieldTypes.find(ft => ft.id === parseInt(checkbox.value));
                    checkbox.checked = fieldType ? fieldType.required : false;
                });
                
                loadProjects(); // 重新加载项目列表
                alert('项目创建成功！');
            } catch (error) {
                console.error('创建项目失败:', error);
                alert('创建项目失败: ' + error.message);
            }
        });

        // 生成管理员专属二维码
        async function generateMyQRCode(projectId, projectName) {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }

            try {
                const response = await fetch(`/project-shares/project/${projectId}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const projectShare = await response.json();
                    showQRCode(projectShare.qrCodeData, projectName, projectShare.shareToken);
                } else {
                    const error = await response.json();
                    alert('生成二维码失败: ' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('生成二维码失败:', error);
                alert('生成二维码失败: ' + error.message);
            }
        }

        // 显示QR码
        function showQRCode(qrCodeData, projectName, shareToken = null) {
            const container = document.getElementById('qr-code-container');
            const shareInfo = shareToken ? `<p class="text-muted small">分享标识: ${shareToken}</p>` : '';
            container.innerHTML = `
                <h6>${projectName}</h6>
                <img src="${qrCodeData}" class="img-fluid qr-code" alt="项目二维码" id="qrCodeImage">
                ${shareInfo}
                <p class="text-info small mt-2">用户扫描此二维码提交的数据将关联到您的账户</p>
                <div class="mt-3">
                    <button class="btn btn-outline-primary btn-sm" onclick="downloadQRCodeImage('${qrCodeData}', '${projectName}')">
                        <i class="bi bi-download"></i> 下载二维码
                    </button>
                </div>
            `;
            new bootstrap.Modal(document.getElementById('qrCodeModal')).show();
        }

        // 查看项目详情
        async function viewProject(projectId) {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }

            try {
                // 获取或创建项目分享
                const response = await fetch(`/project-shares/project/${projectId}`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const projectShare = await response.json();
                    // 跳转到用户提交页面（二维码扫描后的页面）
                    window.location.href = `submit.html?share=${projectShare.shareToken}`;
                } else {
                    const error = await response.json();
                    alert('获取项目分享失败: ' + (error.message || '未知错误'));
                }
            } catch (error) {
                console.error('获取项目分享失败:', error);
                alert('获取项目分享失败: ' + error.message);
            }
        }

        // 编辑项目
        async function editProject(projectId) {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }

            try {
                // 获取项目详情
                const response = await fetch(`/projects/${projectId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    throw new Error('获取项目详情失败');
                }

                const project = await response.json();
                
                // 初始化编辑项目的Quill编辑器（如果还没有初始化）
                if (!editQuill) {
                    editQuill = new Quill('#edit-project-description-editor', {
                        theme: 'snow',
                        placeholder: '请输入项目介绍...',
                        modules: {
                            toolbar: [
                                ['bold', 'italic', 'underline'],
                                ['link'],
                                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                                ['clean']
                            ]
                        }
                    });
                }
                
                // 填充编辑表单
                document.getElementById('edit-project-id').value = project.id;
                document.getElementById('edit-project-name').value = project.name;
                editQuill.root.innerHTML = project.description || '';
                
                // 显示当前图片
                const currentImageDiv = document.getElementById('edit-current-image');
                const currentImagePreview = document.getElementById('edit-current-image-preview');
                if (project.mainImage) {
                    currentImagePreview.src = project.mainImage;
                    currentImageDiv.style.display = 'block';
                } else {
                    currentImageDiv.style.display = 'none';
                }
                
                // 隐藏新图片预览
                document.getElementById('edit-image-preview').style.display = 'none';
                
                // 加载字段类型选择
                loadEditFieldTypes(project.fieldTypes || []);
                
                // 显示编辑模态框
                new bootstrap.Modal(document.getElementById('editProjectModal')).show();
            } catch (error) {
                console.error('加载项目详情失败:', error);
                alert('加载项目详情失败: ' + error.message);
            }
        }

        // 加载编辑模态框的字段类型
        function loadEditFieldTypes(selectedFieldTypes) {
            const container = document.getElementById('edit-field-types-container');
            container.innerHTML = '';

            const enabledFieldTypes = fieldTypes.filter(ft => ft.enabled);
            const selectedIds = selectedFieldTypes.map(ft => ft.id);

            enabledFieldTypes.forEach(fieldType => {
                const fieldDiv = document.createElement('div');
                fieldDiv.className = 'form-check mb-2';
                const isChecked = selectedIds.includes(fieldType.id);
                fieldDiv.innerHTML = `
                    <input class="form-check-input" type="checkbox" id="edit-field-${fieldType.key}" name="editFieldTypes" value="${fieldType.id}" ${isChecked ? 'checked' : ''}>
                    <label class="form-check-label" for="edit-field-${fieldType.key}">${fieldType.label}</label>
                `;
                container.appendChild(fieldDiv);
            });
        }

        // 编辑图片预览
        document.getElementById('edit-main-image').addEventListener('change', function(e) {
            const file = e.target.files[0];
            const preview = document.getElementById('edit-image-preview');
            const previewImg = document.getElementById('edit-image-preview-img');
            const sizeInfo = document.getElementById('edit-image-size-info');
            
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    preview.style.display = 'block';
                    if (sizeInfo) {
                        const sizeMB = (file.size / (1024 * 1024)).toFixed(2);
                        sizeInfo.textContent = `文件大小：${sizeMB}MB`;
                    }
                };
                reader.readAsDataURL(file);
            } else {
                preview.style.display = 'none';
                if (sizeInfo) sizeInfo.textContent = '';
            }
        });

        // 保存编辑
        document.getElementById('save-edit-project').addEventListener('click', async function() {
            const projectId = document.getElementById('edit-project-id').value;
            const projectName = document.getElementById('edit-project-name').value.trim();
            const projectDescription = editQuill ? editQuill.root.innerHTML.trim() : '';
            const mainImageFile = document.getElementById('edit-main-image').files[0];
            const selectedFieldTypeIds = Array.from(document.querySelectorAll('input[name="editFieldTypes"]:checked')).map(cb => parseInt(cb.value));
            
            if (!projectName) {
                alert('请输入项目名称');
                return;
            }
            
            if (selectedFieldTypeIds.length === 0) {
                alert('请至少选择一个表单字段');
                return;
            }
            
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                return;
            }
            let mainImagePath = null;
            
            try {
                if (!navigator.onLine) {
                    throw new Error('网络连接不可用，请检查网络后重试');
                }
                // 如果有新图片文件，先上传图片
                if (mainImageFile) {
                    // 客户端校验大小、类型与扩展名，减少请求与明确错误提示
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                    const allowedExts = ['.jpg', '.jpeg', '.png', '.gif'];
                    const lowerName = (mainImageFile.name || '').toLowerCase();
                    if (!allowedTypes.includes(mainImageFile.type)) {
                        throw new Error('不支持的图片格式，请使用 JPG、PNG 或 GIF');
                    }
                    if (!allowedExts.some(ext => lowerName.endsWith(ext))) {
                        throw new Error('文件扩展名不被支持，请使用 .jpg / .jpeg / .png / .gif');
                    }
                    if (mainImageFile.size > 10 * 1024 * 1024) {
                        const sizeMB = (mainImageFile.size / (1024 * 1024)).toFixed(2);
                        throw new Error(`图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试`);
                    }

                    const formData = new FormData();
                    formData.append('file', mainImageFile);
                    
                    const uploadResponse = await fetch('/projects/upload', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`
                        },
                        body: formData
                    });
                    
                    if (!uploadResponse.ok) {
                        let serverMessage = '';
                        try {
                            const errData = await uploadResponse.json();
                            serverMessage = errData.message || errData.error || '';
                        } catch (e) {
                            try {
                                serverMessage = await uploadResponse.text();
                            } catch (_) {}
                        }

                        // 按状态码与消息细化提示
                        if (uploadResponse.status === 401) {
                            throw new Error('未登录或登录已过期，请重新登录');
                        }
                        if (uploadResponse.status === 413) {
                            const sizeMB = mainImageFile ? (mainImageFile.size / (1024 * 1024)).toFixed(2) : null;
                            throw new Error(sizeMB ? `图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试` : '图片过大，超过 10MB 限制，请压缩后重试');
                        }
                        if (uploadResponse.status === 415) {
                            throw new Error('媒体类型不被支持，请使用 JPG、PNG 或 GIF');
                        }
                        if (serverMessage.includes('Only image files are allowed')) {
                            throw new Error('不支持的图片格式，请使用 JPG、PNG 或 GIF');
                        }
                        if (serverMessage.includes('No file uploaded')) {
                            throw new Error('未选择图片文件，请先选择后再上传');
                        }
                        if (serverMessage.includes('File too large') || serverMessage.includes('LIMIT_FILE_SIZE')) {
                            const sizeMB = mainImageFile ? (mainImageFile.size / (1024 * 1024)).toFixed(2) : null;
                            throw new Error(sizeMB ? `图片大小为 ${sizeMB}MB，超过 10MB 限制，请压缩后重试` : '图片过大，超过 10MB 限制，请压缩后重试');
                        }
                        if (uploadResponse.status === 500) {
                            throw new Error('服务器内部错误' + (serverMessage ? `：${serverMessage}` : '，请稍后重试或联系管理员'));
                        }

                        throw new Error('图片上传失败' + (serverMessage ? `：${serverMessage}` : `（HTTP ${uploadResponse.status}）`));
                    }
                    
                    const uploadResult = await uploadResponse.json();
                    mainImagePath = uploadResult.path;
                }
                
                // 更新项目
                const projectData = {
                    name: projectName,
                    description: projectDescription || undefined,
                    fieldTypeIds: selectedFieldTypeIds
                };
                
                // 只有在上传了新图片时才包含mainImage字段
                if (mainImagePath) {
                    projectData.mainImage = mainImagePath;
                }
                
                const response = await fetch(`/projects/${projectId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(projectData)
                });
                
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '更新项目失败');
                }
                
                bootstrap.Modal.getInstance(document.getElementById('editProjectModal')).hide();
                loadProjects(); // 重新加载项目列表
                alert('项目更新成功！');
            } catch (error) {
                console.error('更新项目失败:', error);
                alert('更新项目失败: ' + error.message);
            }
        });

        // 下载二维码图片 - 兼容手机端
        function downloadQRCodeImage(qrCodeData, projectName) {
            try {
                // 检测是否为移动设备
                const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
                const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = qrCodeData;
                link.download = `${projectName}_二维码.png`;
                
                if (isMobile) {
                    if (isWeChat) {
                        // 微信浏览器中，显示提示信息
                        alert('请长按二维码图片，选择"保存图片"来下载');
                        return;
                    } else {
                        // 移动端浏览器，尝试直接下载
                        link.target = '_blank';
                    }
                }
                
                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                // 如果是移动端但不是微信，显示备用提示
                if (isMobile && !isWeChat) {
                    setTimeout(() => {
                        alert('如果下载未开始，请长按二维码图片选择"保存图片"');
                    }, 1000);
                }
                
            } catch (error) {
                console.error('下载失败:', error);
                alert('下载失败，请长按二维码图片选择"保存图片"');
            }
        }
    </script>
</body>
</html>